﻿const co = require('co');
const activityDao = require('../../model/act/activity');
const controllerBase = require('../../core/controllerBase');
const errEnum = require("../../common/enum");
const validator = require("validator");
var config = require('../../configuration.json');
// const oredercontroller = require('ordercontroller')
var uuid = require('node-uuid');
var moment = require('moment');
class ActivityController extends controllerBase {
    /*
    * 类构造函数
    * 设置类需要的数据实体操作实例
    */
    constructor(application) {
        ///将对应的数据库实体对象传递至基类
        super(application, new activityDao());
    }

    initializeRouter(instance) {
        //#获取详细记录的路由配置
        this.app.get('/activitys/:id', function (req, res) {
            co(instance.getActivityDetal(req))
                .then(result => instance.responseResult(req, res, result))
                .catch(result => { console.log(result); instance.responseResult(req, res, result); });
        });


        //#获取详细记录的路由配置
        this.app.get('/activitys', function (req, res) {
            let cateid = req.query.cateid || "";
            instance._daoModel.getActivityList(cateid)
                .then(function (result) {
                    if (result.rows != null && result.rows.length == 2) {
                        return res.json({ successed: true, rows: result.rows[0] });
                    } else {
                        return res.json({ successed: false, message: "获取数据失败！" });
                    }
                })
                .catch(function (err) {
                    return res.json({ successed: false, message: "获取数据失败！" });
                });
        });


        //#修改home_base表lphx_id
        this.app.get('/updateHomeBaseLphxId', function (req, res) {
            co(instance.updateHomeBaseLphxId(req, res))
                .then(result => instance.responseResult(req, res, result))
                .catch(result => instance.responseResult(res, res, result))
        });


        //#新增fw_page_share数据
        this.app.post('/addFwPageShare', function (req, res) {
            co(instance.addFwPageShare(req, res))
                .then(result => instance.responseResult(req, res, result))
                .catch(result => instance.responseResult(res, res, result))
        });


        //#修改合并表数据
        this.app.get('/updateTableData', function (req, res) {
            co(instance.updateTableData(req, res))
                .then(result => instance.responseResult(req, res, result))
                .catch(result => instance.responseResult(res, res, result))
        });

    }

    *getActivityDetal(req) {
        console.log(req.session)
        let activityid = req.params.id;
        let sharer = req.query.userid;     // 分享者的uid
        console.log(sharer);
        if (!validator.isUUID(activityid)) return { successed: false, error: 1014, message: errEnum.RESULT_ERROR_ENUM[1014] };
        let channelid = req.query.cid || "";
        let giftid = req.query.gid || "";
        // let openid = req.query.uid || "";
        let userid = req.query.userid || "";

        let result = yield this._daoModel.getDetialById([activityid, channelid, giftid, userid]);

        console.log(result);

        if (result.rows != null && result.rows.length >= 3 && result.rows[0].length > 0) {
            result.rows[0][0].ticket = result.rows[1];
            var temp = new Array();
            var count = 0;
            if (result.rows[2][0].activity_cover) {
                temp[count] = { "img": result.rows[2][0].activity_cover };
                count++;
            }
            if (result.rows[2][0].img1) {
                temp[count] = { "img": result.rows[2][0].img1 };
                count++;
            }
            if (result.rows[2][0].img2) {
                temp[count] = { "img": result.rows[2][0].img2 };
                count++;
            }
            if (result.rows[2][0].img3) {
                temp[count] = { "img": result.rows[2][0].img3 };
                count++;
            }
            if (result.rows[2][0].img4) {
                temp[count] = { "img": result.rows[2][0].img4 };
                count++;
            }
            if (result.rows[2][0].img5) {
                temp[count] = { "img": result.rows[2][0].img5 };
                count++;
            }
            result.rows[0][0].imgs = temp;
            // result.rows[0][0].imgs = result.rows[2];
            // console.log("----------->"+result.rows[2][0].activity_cover);
            let outputData = { successed: true, rows: result.rows[0] };
            return outputData;
        }
    }
    

    //修改home_base表lphx_id
    * updateHomeBaseLphxId(req, res) {
        let sqlHomeBaseHx = `select id,pid from home_base_hx where del=0`
        let resultHomeBaseHx = yield this._daoModel.query(sqlHomeBaseHx);
        let arrHomeBaseHx= resultHomeBaseHx.rows
        let sqlHBId = `select pid from home_base_hx GROUP BY pid HAVING pid is not NULL`
        let resultHBId= yield this._daoModel.query(sqlHBId);
        let arrHBId= resultHBId.rows
        for (let i = 0; i < arrHBId.length; i++) {
            let hbId=arrHBId[i].pid;
            let lphx_id="";
            if(hbId){
                for (let a = 0; a < arrHomeBaseHx.length; a++) {
                    let hxpid=arrHomeBaseHx[a].pid;
                    let hxid=arrHomeBaseHx[a].id;
                    if(hbId==hxpid){
                        lphx_id+=","+hxid
                    }
                }
            }
            lphx_id=lphx_id.substring(1,lphx_id.length)
            let sqlUpdateHomeBase = `update home_base set lphx_id='${lphx_id}' where id=${hbId}`
            let resulUpdateHomeBasex = yield this._daoModel.query(sqlUpdateHomeBase);
        }
        return { code: 1, successed: true,msg:"修改成功！"}
    }


    //新增fw_page_share数据
    * addFwPageShare(req, res) {
        let share_id=uuid.v4();//记录id
        let user_id=req.body.user_id;//用户id
        let parent_id=req.body.parent_id;//记录id
        // let share_date=req.body.share_date;//分享日期
        let share_url=req.body.share_url;//分享链接
        let share_bus=req.body.share_bus;//分享业务类型 1楼盘  2文章
        let data_id=req.body.data_id;//业务数据id
        let share_title=req.body.share_title;//分享标题
        if(user_id){
        let sql = `INSERT INTO fw_page_share(share_id,parent_id,user_id,share_date,share_url,share_bus,data_id,share_title)
            VALUES('${share_id}','${parent_id}','${user_id}',NOW(),'',${share_bus},'','${share_title}')`
            let resultHome = yield this._daoModel.query(sql);
            return { code: 1, successed: true}
        }else{
            return { code: 0, successed: false}
        }
    }

    //#修改合并表数据
    * updateTableData(req, res) {
        let r = {}
        let str=''
        //设置省市数据
        let sf='广东省';
        let province='8a75a8b6-3759-47a4-9ff2-3a63fa508208';
        // let sq='肇庆市';
        // let city='7558051e-7511-4d53-befa-56ea54e2e8d4';//肇庆市
        let sq='佛山市';
        let city='61733a8a-f10c-4934-ae87-c5dd08d85a97';//佛山市

        //查询haojia_loupan_copy1表
        let sqlXin = `SELECT * FROM haojia_loupan_copy1`
        let resultXin = yield this._daoModel.query(sqlXin);
        let arrHomeBaseXin = resultXin.rows

        //查询home_base表
        // let sqlJiu = `SELECT * FROM home_base WHERE link LIKE '%zhaoqing%'`//肇庆
        let sqlJiu = `SELECT * FROM home_base WHERE link LIKE '%fs.newhouse.fang%'`//佛山
        let resultJiu = yield this._daoModel.query(sqlJiu);
        let arrHomeBaseJiu = resultJiu.rows

        for (let i = 0; i < arrHomeBaseXin.length; i++) {
            let num = 0;
            let xinID = arrHomeBaseXin[i].id;
            let xinName = arrHomeBaseXin[i].title;
            //表数据开始
            let Xinid = arrHomeBaseXin[i].id
            let title = arrHomeBaseXin[i].title
            let bieming = arrHomeBaseXin[i].bieming
            let junjia = arrHomeBaseXin[i].junjia
            let leixing = arrHomeBaseXin[i].leixing
            let xingshi = arrHomeBaseXin[i].xingshi
            let zhuangxiu = arrHomeBaseXin[i].zhuangxiu
            let area = arrHomeBaseXin[i].area
            let kaifashang = arrHomeBaseXin[i].kaifashang
            let address = arrHomeBaseXin[i].address
            let chanquan = arrHomeBaseXin[i].chanquan
            let status_sell = arrHomeBaseXin[i].status_sell
            let address_shoulouchu = arrHomeBaseXin[i].address_shoulouchu
            let jiegou = arrHomeBaseXin[i].jiegou
            let tese = arrHomeBaseXin[i].tese
            let kaipan = arrHomeBaseXin[i].kaipan
            let jiaolou = arrHomeBaseXin[i].jiaolou
            let chewei = arrHomeBaseXin[i].chewei
            let wuyefei = arrHomeBaseXin[i].wuyefei
            let wuyefei_desc = arrHomeBaseXin[i].wuyefei_desc
            let bieshu = arrHomeBaseXin[i].bieshu
            let bieshu_desc = arrHomeBaseXin[i].bieshu_desc
            let wuye = arrHomeBaseXin[i].wuye
            let lvhualv = arrHomeBaseXin[i].lvhualv
            let rongjilv = arrHomeBaseXin[i].rongjilv
            let dongshu = arrHomeBaseXin[i].dongshu
            let hushu = arrHomeBaseXin[i].hushu
            let mianji = arrHomeBaseXin[i].mianji
            let louceng = arrHomeBaseXin[i].louceng
            let jianzumianji = arrHomeBaseXin[i].jianzumianji
            let dongju_max = arrHomeBaseXin[i].dongju_max
            let chaoxiang = arrHomeBaseXin[i].chaoxiang
            let dongju_min = arrHomeBaseXin[i].dongju_min
            let status_gongcheng = arrHomeBaseXin[i].status_gongcheng
            let sheji = arrHomeBaseXin[i].sheji
            let daili = arrHomeBaseXin[i].daili
            let shigong = arrHomeBaseXin[i].shigong
            let quwei = arrHomeBaseXin[i].quwei
            let guihua = arrHomeBaseXin[i].guihua
            let jingguan = arrHomeBaseXin[i].jingguan
            let fengge = arrHomeBaseXin[i].fengge
            let desc = arrHomeBaseXin[i].desc
            let peibei = arrHomeBaseXin[i].peibei
            let create_time = moment(arrHomeBaseXin[i].create_time).format('YYYY-MM-DD')
            let update_time = moment(arrHomeBaseXin[i].update_time).format('YYYY-MM-DD')
            let status = arrHomeBaseXin[i].status
            let seo_title = arrHomeBaseXin[i].seo_title
            let seo_keyword = arrHomeBaseXin[i].seo_keyword
            let seo_desc = arrHomeBaseXin[i].seo_desc
            let pic = arrHomeBaseXin[i].pic
            let pics = arrHomeBaseXin[i].pics
            let pid = arrHomeBaseXin[i].pid
            let sort = arrHomeBaseXin[i].sort
            let video = arrHomeBaseXin[i].video
            let tel = arrHomeBaseXin[i].tel
            let kaipan_date = moment(arrHomeBaseXin[i].kaipan_date).format('YYYY-MM-DD')
            let lat = arrHomeBaseXin[i].lat
            let lng = arrHomeBaseXin[i].lng
            let rooms = arrHomeBaseXin[i].rooms
            let total_min = arrHomeBaseXin[i].total_min;
            let total_max = arrHomeBaseXin[i].total_max;
            if(total_min){
                total_min=total_min/10000
            }
            if(total_max){
                total_max=total_max/10000
            }
            let price = arrHomeBaseXin[i].price
            let mianji_min = arrHomeBaseXin[i].mianji_min
            let mianji_max = arrHomeBaseXin[i].mianji_max
            let tag = arrHomeBaseXin[i].tag
            let ishot = arrHomeBaseXin[i].ishot
            let viewcount = arrHomeBaseXin[i].viewcount
            let city_id = arrHomeBaseXin[i].city_id
            let pic_alt = arrHomeBaseXin[i].pic_alt
            let pics_shoulou = arrHomeBaseXin[i].pics_shoulou
            let pics_yangban = arrHomeBaseXin[i].pics_yangban
            let pics_jiaotong = arrHomeBaseXin[i].pics_jiaotong
            let pics_peitao = arrHomeBaseXin[i].pics_peitao
            let pics_shapan = arrHomeBaseXin[i].pics_shapan
            let pics_guihua = arrHomeBaseXin[i].pics_guihua
            let pics_xiaoguo = arrHomeBaseXin[i].pics_xiaoguo
            let pics_zhengzhao = arrHomeBaseXin[i].pics_zhengzhao
            let pics_tuiguang = arrHomeBaseXin[i].pics_tuiguang
            let price_txt = arrHomeBaseXin[i].price_txt
            let ditie = arrHomeBaseXin[i].ditie
            let yushouzheng = arrHomeBaseXin[i].yushouzheng
            let tel2 = arrHomeBaseXin[i].tel2
            let address_area = arrHomeBaseXin[i].address_area
            let s_status = arrHomeBaseXin[i].s_status
            let updator = arrHomeBaseXin[i].updator
            let tips = arrHomeBaseXin[i].tips
            let tips_limit_time = moment(arrHomeBaseXin[i].tips_limit_time).format('YYYY-MM-DD')
            let yuyue_count = arrHomeBaseXin[i].yuyue_count
            let baoming_count = arrHomeBaseXin[i].baoming_count
            let zutuan_count = arrHomeBaseXin[i].zutuan_count
            let site_id = arrHomeBaseXin[i].site_id
            let company_id = arrHomeBaseXin[i].company_id
            let desc_zhoubian = arrHomeBaseXin[i].desc_zhoubian
            let desc_youshi = arrHomeBaseXin[i].desc_youshi
            let deptId = arrHomeBaseXin[i].deptId
            let lpid = arrHomeBaseXin[i].lpid
            //表数据结束
            //转换销售状态
            let xszt=0;
            if(status_sell==0){
                xszt=1;
            }else if(status_sell==1){
                xszt=0;
            }else{
                xszt=4;
            }

            //转换删除状态
            let haojiadel=0;
            if(status==0){
                haojiadel=1;
            }else{
                haojiadel=0;
            }


            //分割图片开始
            let pics_shoulou_arr = [];
            let pics_yangban_arr = [];
            let pics_jiaotong_arr = [];
            let pics_peitao_arr = [];
            let pics_shapan_arr = [];
            let pics_guihua_arr = [];
            let pics_xiaoguo_arr = [];
            let pics_zhengzhao_arr = [];
            let pics_tuiguang_arr = [];
            let pics_shijingtu_arr = [];//实景图
            if(pics_shoulou){
                pics_shoulou_arr=pics_shoulou.split("|");
            }
            if(pics_yangban){
                pics_yangban_arr=pics_yangban.split("|");
            }
            if(pics_jiaotong){
                pics_jiaotong_arr=pics_jiaotong.split("|");
            }
            if(pics_peitao){
                pics_peitao_arr=pics_peitao.split("|");
            }
            if(pics_shapan){
                pics_shapan_arr=pics_shapan.split("|");
            }
            if(pics_guihua){
                pics_guihua_arr=pics_guihua.split("|");
            }
            if(pics_xiaoguo){
                pics_xiaoguo_arr=pics_xiaoguo.split("|");
            }
            if(pics_zhengzhao){
                pics_zhengzhao_arr=pics_zhengzhao.split("|");
            }
            if(pics_tuiguang){
                pics_tuiguang_arr=pics_tuiguang.split("|");
            }
            if(pics){
                pics_shijingtu_arr=pics.split("|");
            }
            //分割图片结束

             //查询home_kfs表
            let sqlkfs = `SELECT id,name FROM home_kfs`
            let resultkfs = yield this._daoModel.query(sqlkfs);
            let arrHomeBaseKfs = resultkfs.rows
            //查询home_wylx表
            let sqlwylx = `SELECT id,name FROM home_wylx`
            let resultwylx = yield this._daoModel.query(sqlwylx);
            let arrHomeBaseWylx = resultwylx.rows
            //查询home_jzlx表
            let sqljzlx = `SELECT id,name FROM home_jzlx`
            let resultjzlx = yield this._daoModel.query(sqljzlx);
            let arrHomeBaseJzlx = resultjzlx.rows

            //获取id
            let kfsid=0;
            let wylxid=0;
            let jzlxid=0;
            //判断
            let kfsPdNum=0;
            let wylxPdNum=0;
            let jzlxPdNum=0;
            //获取home_kfs的id
            for(let e=0;e<arrHomeBaseKfs.length; e++){
                let id=arrHomeBaseKfs[e].id
                let name=arrHomeBaseKfs[e].name
                if(kaifashang==name){
                    kfsid=id
                    kfsPdNum=1
                }
            }
            //获取home_wylx的id
            for(let e=0;e<arrHomeBaseWylx.length; e++){
                let id=arrHomeBaseWylx[e].id
                let name=arrHomeBaseWylx[e].name
                if(leixing==name){
                    wylxid=id
                    wylxPdNum=1
                }
            }
            //获取home_jzlx的id
            for(let e=0;e<arrHomeBaseJzlx.length; e++){
                let id=arrHomeBaseJzlx[e].id
                let name=arrHomeBaseJzlx[e].name
                if(xingshi==name){
                    jzlxid=id
                    jzlxPdNum=1
                }
            }
            //物业类型，建筑类型，开发商没有时添加数据
            if(kfsPdNum==0){
                if(kaifashang&&kaifashang!=''&&kaifashang!='null'){
                    let addTableSql = `INSERT INTO home_kfs(name) VALUES('${kaifashang}');`
                    let resultaddTable = yield this._daoModel.query(addTableSql);
                    let idt =resultaddTable.rows.insertId;
                    kfsid=idt
                }

            }
            if(wylxPdNum==0){
                if(leixing&&leixing!=''&&leixing!='null'){
                    let addTableSql = `INSERT INTO home_wylx(name) VALUES('${leixing}');`
                    let resultaddTable = yield this._daoModel.query(addTableSql);
                    let idt =resultaddTable.rows.insertId;
                    wylxid=idt
                }

            }
            if(jzlxPdNum==0){
                if(xingshi&&xingshi!=''&&xingshi!='null'){
                                let addTableSql = `INSERT INTO home_jzlx(name) VALUES('${xingshi}');`
                                let resultaddTable = yield this._daoModel.query(addTableSql);
                                let idt =resultaddTable.rows.insertId;
                                jzlxid=idt
                }
                
            }

            //数据合并开始
            for (let a = 0; a < arrHomeBaseJiu.length; a++) {
                let jiuID = arrHomeBaseJiu[a].id;
                let jiuName = arrHomeBaseJiu[a].name;
                if (xinName == jiuName) {
                    str+='homebaseid='+jiuID+',';
                    str+='haojiaid='+Xinid+',';
                    str+='name='+jiuName+',';
                    console.log('===='+kaipan_date)
                    num=1;
                    let updateSql =``;
                    let connectText=``;
                    //拼接开始
                    if(zhuangxiu&&zhuangxiu.trim()!=''&&zhuangxiu!='null'){
                        connectText+=`zxqk='${zhuangxiu}', ` 
                    }  
                    if(address&&address.trim()!=''&&address!='null'){
                        connectText+=`address='${address}',` 
                    }
                    if(chanquan&&chanquan.trim()!=''&&chanquan!='null'){
                        connectText+=`cqnx='${chanquan}',` 
                    }
                    if(address_shoulouchu&&address_shoulouchu.trim()!=''&&address_shoulouchu!='null'){
                        connectText+=`sldz='${address_shoulouchu}',` 
                    } 
                    if(tese&&tese.trim()!=''&&tese!='null'){
                        connectText+=`tags='${tese}',` 
                    } 
                    if(chewei&&chewei.trim()!=''&&chewei!='null'){
                        connectText+=`cwqk='${chewei}',` 
                    }
                    if(wuyefei&&wuyefei.trim()!=''&&wuyefei!='null'){
                        connectText+=`wyf='${wuyefei}',` 
                    }
                    if(wuye&&wuye.trim()!=''&&wuye!='null'){
                        connectText+=`wygs='${wuye}',` 
                    }
                    if(lvhualv&&lvhualv.trim()!=''&&lvhualv!='null'){
                        connectText+=`lhl='${lvhualv}',` 
                    }
                    if(rongjilv&&rongjilv.trim()!=''&&rongjilv!='null'){
                        connectText+=`rjl='${rongjilv}',` 
                    }
                    if(hushu&&hushu.trim()!=''&&hushu!='null'){
                        connectText+=`zhs='${hushu}',` 
                    } 
                    if(mianji&&mianji.trim()!=''&&mianji!='null'){
                        connectText+=`zdmj='${mianji}',` 
                    }
                    if(louceng&&louceng.trim()!=''&&louceng!='null'){
                        connectText+=`lczk='${louceng}',` 
                    } 
                    if(jianzumianji&&jianzumianji.trim()!=''&&jianzumianji!='null'){
                        connectText+=`jzmj='${jianzumianji}',` 
                    }
                    if(kaipan_date&&kaipan_date.trim()!=''&&kaipan_date!='null'){
                        connectText+=`kpsj='${kaipan_date}',` 
                    }
                    if(lat&&lat.trim()!=''&&lat!='null'){
                        connectText+=`lat='${lat}',` 
                    }
                    if(lng&&lng.trim()!=''&&lng!='null'){
                        connectText+=`lon='${lng}',` 
                    }
                    if(price&&price!=0&&price!='null'){
                        connectText+=`xsjg='${price}',` 
                    }
                    if(ditie&&ditie.trim()!=''&&ditie!='null'){
                        connectText+=`dtqk='${ditie}',` 
                    }
                    if(pic&&pic.trim()!=''&&pic!='null'){
                        connectText+=`pics='${pic}',` 
                    }
                    if(tel&&tel.trim()!=''&&tel!='null'){
                        connectText+=`phone='${tel}',` 
                    }
                    //拼接结束
                    updateSql = `UPDATE home_base set 
                    wylx_id='${wylxid}',
                    wylx='${leixing}',
                    jzlx='${xingshi}',
                    jzlx_id='${jzlxid}',
                    kfs='${kaifashang}',
                    kfs_id='${kfsid}',    
                    `+connectText+`
                    lpid='${Xinid}',
                    bieming='${bieming}',
                    wuyefei_desc='${wuyefei}',
                    bieshu='${bieshu}',
                    bieshu_desc='${bieshu_desc}',
                    dongju_max='${dongju_max}',
                    chaoxiang='${chaoxiang}',
                    dongju_min='${dongju_min}',
                    status_gongcheng='${status_gongcheng}',
                    sheji='${sheji}',
                    daili='${daili}',
                    shigong='${shigong}',
                    quwei='${quwei}',
                    guihua='${guihua}',
                    jingguan='${jingguan}',
                    fengge='${fengge}',
                    home_base.desc='${desc}',
                    peibei='${peibei}',
                    create_time='${create_time}',
                    update_time='${update_time}',
                    seo_title='${seo_title}',
                    seo_keyword='${seo_keyword}',
                    seo_desc='${seo_desc}',
                    pic='${pics}',
                    pid='${pid}',
                    rooms='${rooms}',
                    total_min='${total_min}',
                    total_max='${total_max}',
                    mianji_max=${mianji_max},
                    mianji_min=${mianji_min},
                    tag='${tag}',
                    ishot=${ishot},
                    viewcount=${viewcount},
                    price_txt='${price_txt}',
                    tel2='${tel2}',
                    address_area='${address_area}',
                    s_status=${s_status},
                    updator=${updator},
                    tips='${tips}',
                    tips_limit_time='${tips_limit_time}',
                    yuyue_count=${yuyue_count},
                    baoming_count=${baoming_count},
                    zutuan_count=${zutuan_count},
                    site_id=${site_id},
                    company_id=${company_id},
                    desc_zhoubian='${desc_zhoubian}',
                    desc_youshi='${desc_youshi}',
                    deptId='${deptId}'
                    where id=${jiuID}`
                    let resultupdate = yield this._daoModel.query(updateSql);


                    //插入source_list表数据
                // let pics_shoulou_arr = [];
                for(let x=0;x<pics_shoulou_arr.length;x++){
                    let path=pics_shoulou_arr[x];
                    let addsql = `INSERT INTO source_list(pid, path, img, lppic_type, source_type, pic_alt, loupan_id)
                    VALUES ('${jiuID}', '${path}', '${path}', '13', '1',  '${pic_alt}','${Xinid}')`
                    let resultadd = yield this._daoModel.query(addsql);
                }
                // let pics_yangban_arr = [];
                for(let x=0;x<pics_yangban_arr.length;x++){
                    let path=pics_yangban_arr[x];
                    let addsql = `INSERT INTO source_list(pid, path, img, lppic_type, source_type, pic_alt, loupan_id)
                    VALUES ('${jiuID}', '${path}', '${path}', '9', '1',  '${pic_alt}','${Xinid}')`
                    let resultadd = yield this._daoModel.query(addsql);
                }
                // let pics_jiaotong_arr = [];
                for(let x=0;x<pics_jiaotong_arr.length;x++){
                    let path=pics_jiaotong_arr[x];
                    let addsql = `INSERT INTO source_list(pid, path, img, lppic_type, source_type, pic_alt, loupan_id)
                    VALUES ('${jiuID}', '${path}', '${path}', '6', '1',  '${pic_alt}','${Xinid}')`
                    let resultadd = yield this._daoModel.query(addsql);
                }
                // let pics_peitao_arr = [];
                for(let x=0;x<pics_peitao_arr.length;x++){
                    let path=pics_peitao_arr[x];
                    let addsql = `INSERT INTO source_list(pid, path, img, lppic_type, source_type, pic_alt, loupan_id)
                    VALUES ('${jiuID}', '${path}', '${path}', '7', '1',  '${pic_alt}','${Xinid}')`
                    let resultadd = yield this._daoModel.query(addsql);
                }
                // let pics_shapan_arr = [];
                for(let x=0;x<pics_shapan_arr.length;x++){
                    let path=pics_shapan_arr[x];
                    let addsql = `INSERT INTO source_list(pid, path, img, lppic_type, source_type, pic_alt, loupan_id)
                    VALUES ('${jiuID}', '${path}', '${path}', '14', '1',  '${pic_alt}','${Xinid}')`
                    let resultadd = yield this._daoModel.query(addsql);
                }
                // let pics_guihua_arr = [];
                for(let x=0;x<pics_guihua_arr.length;x++){
                    let path=pics_guihua_arr[x];
                    let addsql = `INSERT INTO source_list(pid, path, img, lppic_type, source_type, pic_alt, loupan_id)
                    VALUES ('${jiuID}', '${path}', '${path}', '15', '1',  '${pic_alt}','${Xinid}')`
                    let resultadd = yield this._daoModel.query(addsql);
                }
                // let pics_xiaoguo_arr = [];
                for(let x=0;x<pics_xiaoguo_arr.length;x++){
                    let path=pics_xiaoguo_arr[x];
                    let addsql = `INSERT INTO source_list(pid, path, img, lppic_type, source_type, pic_alt, loupan_id)
                    VALUES ('${jiuID}', '${path}', '${path}', '1', '1',  '${pic_alt}','${Xinid}')`
                    let resultadd = yield this._daoModel.query(addsql);
                }
                // let pics_zhengzhao_arr = [];
                for(let x=0;x<pics_zhengzhao_arr.length;x++){
                    let path=pics_zhengzhao_arr[x];
                    let addsql = `INSERT INTO source_list(pid, path, img, lppic_type, source_type, pic_alt, loupan_id)
                    VALUES ('${jiuID}', '${path}', '${path}', '16', '1',  '${pic_alt}','${Xinid}')`
                    let resultadd = yield this._daoModel.query(addsql);
                }
                // let pics_tuiguang_arr = [];
                for(let x=0;x<pics_tuiguang_arr.length;x++){
                    let path=pics_tuiguang_arr[x];
                    let addsql = `INSERT INTO source_list(pid, path, img, lppic_type, source_type, pic_alt, loupan_id)
                    VALUES ('${jiuID}', '${path}', '${path}', '17', '1',  '${pic_alt}','${Xinid}')`
                    let resultadd = yield this._daoModel.query(addsql);
                }

                // let pics_shijingtu_arr = [];//2
                for(let x=0;x<pics_shijingtu_arr.length;x++){
                    let path=pics_shijingtu_arr[x];
                    let addsql = `INSERT INTO source_list(pid, path, img, lppic_type, source_type, pic_alt, loupan_id)
                    VALUES ('${jiuID}', '${path}', '${path}', '5', '1',  '${pic_alt}','${Xinid}')`
                    let resultadd = yield this._daoModel.query(addsql);
                }
                //插入source_list表数据结束





                }
            }
            //数据库原本不存在此数据时执行添加
            if (num == 0) {
                console.log('===='+kaipan_date)
                let addsql = `INSERT INTO home_base (phone,note,name, pics, address, xszt, tags, xsjg, wylx_id, wylx, cqnx, kfs_id, kpsj, jfsj, smzh, zdmj, jzmj, rjl, lhl, jzlx_id, jzlx, cwqk, dtqk, vids, zxqk, wygs, kfs, del, wyf, province, city, sf, sq, qy,  lon, lat, sldz, ldzs, zhs, lczk, bieming, jiegou, wuyefei_desc, bieshu, bieshu_desc, dongju_max, dongju_min, chaoxiang, status_gongcheng, sheji, daili, shigong, quwei, guihua, jingguan, fengge, peibei, create_time, update_time, seo_title, seo_keyword, seo_desc, pic, pid, kaipan_date, rooms, total_min, total_max, mianji_min, mianji_max, tag, ishot, viewcount, price_txt, tel2, address_area, s_status, updator, tips, tips_limit_time, yuyue_count, baoming_count, zutuan_count, site_id, company_id, desc_zhoubian, desc_youshi, deptId, lpid)
                VALUES ('${tel}','合并数据','${title}','${pic}','${address}','${xszt}','${tese}','${price}','${wylxid}','${leixing}','${chanquan}','${kfsid}','${kaipan}','${jiaolou}','','${mianji}','${jianzumianji}','${rongjilv}','${lvhualv}','${jzlxid}',
                '${xingshi}','${chewei}','${ditie}','${video}','${zhuangxiu}','${wuye}','${kaifashang}','${haojiadel}','${wuyefei}','${province}','${city}','${sf}','${sq}','${area}','${lng}','${lat}','${address_shoulouchu}','${dongshu}','${hushu}','${louceng}','${bieming}','${jiegou}','${wuyefei_desc}','${bieshu}','${bieshu_desc}','${dongju_max}','${dongju_min}','${chaoxiang}','${status_gongcheng}','${sheji}','${daili}','${shigong}','${quwei}','${guihua}','${jingguan}','${fengge}','${peibei}', '${create_time}', '${update_time}', '${seo_title}', '${seo_keyword}', '${seo_desc}', '${pics}', '${pid}', '${kaipan_date}', '${rooms}', '${total_min}', '${total_max}', '${mianji_min}', '${mianji_max}', '${tag}', '${ishot}', '${viewcount}', '${price_txt}', '${tel2}', '${address_area}', '${s_status}', '${updator}', '${tips}', '${tips_limit_time}', '${yuyue_count}', '${baoming_count}', '${zutuan_count}', '${site_id}', '${company_id}', '${desc_zhoubian}', '${desc_youshi}', '${deptId}', '${Xinid}')`
                let resultadd = yield this._daoModel.query(addsql);
                let id =resultadd.rows.insertId;
                str+='homebaseid='+id+',';
                str+='haojiaid='+Xinid+',';
                str+='name='+title+',';
                //插入source_list表数据
                // let pics_shoulou_arr = [];
                for(let x=0;x<pics_shoulou_arr.length;x++){
                    let path=pics_shoulou_arr[x];
                    let addsql = `INSERT INTO source_list(pid, path, img, lppic_type, source_type, pic_alt, loupan_id)
                    VALUES ('${id}', '${path}', '${path}', '13', '1',  '${pic_alt}','${Xinid}')`
                    let resultadd = yield this._daoModel.query(addsql);
                }
                // let pics_yangban_arr = [];
                for(let x=0;x<pics_yangban_arr.length;x++){
                    let path=pics_yangban_arr[x];
                    let addsql = `INSERT INTO source_list(pid, path, img, lppic_type, source_type, pic_alt, loupan_id)
                    VALUES ('${id}', '${path}', '${path}', '9', '1',  '${pic_alt}','${Xinid}')`
                    let resultadd = yield this._daoModel.query(addsql);
                }
                // let pics_jiaotong_arr = [];
                for(let x=0;x<pics_jiaotong_arr.length;x++){
                    let path=pics_jiaotong_arr[x];
                    let addsql = `INSERT INTO source_list(pid, path, img, lppic_type, source_type, pic_alt, loupan_id)
                    VALUES ('${id}', '${path}', '${path}', '6', '1',  '${pic_alt}','${Xinid}')`
                    let resultadd = yield this._daoModel.query(addsql);
                }
                // let pics_peitao_arr = [];
                for(let x=0;x<pics_peitao_arr.length;x++){
                    let path=pics_peitao_arr[x];
                    let addsql = `INSERT INTO source_list(pid, path, img, lppic_type, source_type, pic_alt, loupan_id)
                    VALUES ('${id}', '${path}', '${path}', '7', '1',  '${pic_alt}','${Xinid}')`
                    let resultadd = yield this._daoModel.query(addsql);
                }
                // let pics_shapan_arr = [];
                for(let x=0;x<pics_shapan_arr.length;x++){
                    let path=pics_shapan_arr[x];
                    let addsql = `INSERT INTO source_list(pid, path, img, lppic_type, source_type, pic_alt, loupan_id)
                    VALUES ('${id}', '${path}', '${path}', '14', '1',  '${pic_alt}','${Xinid}')`
                    let resultadd = yield this._daoModel.query(addsql);
                }
                // let pics_guihua_arr = [];
                for(let x=0;x<pics_guihua_arr.length;x++){
                    let path=pics_guihua_arr[x];
                    let addsql = `INSERT INTO source_list(pid, path, img, lppic_type, source_type, pic_alt, loupan_id)
                    VALUES ('${id}', '${path}', '${path}', '15', '1',  '${pic_alt}','${Xinid}')`
                    let resultadd = yield this._daoModel.query(addsql);
                }
                // let pics_xiaoguo_arr = [];
                for(let x=0;x<pics_xiaoguo_arr.length;x++){
                    let path=pics_xiaoguo_arr[x];
                    let addsql = `INSERT INTO source_list(pid, path, img, lppic_type, source_type, pic_alt, loupan_id)
                    VALUES ('${id}', '${path}', '${path}', '1', '1',  '${pic_alt}','${Xinid}')`
                    let resultadd = yield this._daoModel.query(addsql);
                }
                // let pics_zhengzhao_arr = [];
                for(let x=0;x<pics_zhengzhao_arr.length;x++){
                    let path=pics_zhengzhao_arr[x];
                    let addsql = `INSERT INTO source_list(pid, path, img, lppic_type, source_type, pic_alt, loupan_id)
                    VALUES ('${id}', '${path}', '${path}', '16', '1',  '${pic_alt}','${Xinid}')`
                    let resultadd = yield this._daoModel.query(addsql);
                }
                // let pics_tuiguang_arr = [];
                for(let x=0;x<pics_tuiguang_arr.length;x++){
                    let path=pics_tuiguang_arr[x];
                    let addsql = `INSERT INTO source_list(pid, path, img, lppic_type, source_type, pic_alt, loupan_id)
                    VALUES ('${id}', '${path}', '${path}', '17', '1',  '${pic_alt}','${Xinid}')`
                    let resultadd = yield this._daoModel.query(addsql);
                }
                // let pics_shijingtu_arr = [];//2
                for(let x=0;x<pics_shijingtu_arr.length;x++){
                    let path=pics_shijingtu_arr[x];
                    let addsql = `INSERT INTO source_list(pid, path, img, lppic_type, source_type, pic_alt, loupan_id)
                    VALUES ('${id}', '${path}', '${path}', '5', '1',  '${pic_alt}','${Xinid}')`
                    let resultadd = yield this._daoModel.query(addsql);
                }
                //插入source_list表数据结束
            }
        }

        //查询haojia_huxing_copy1表
        let sqlhuxing = `SELECT * FROM haojia_huxing_copy1`
        let hxResult = yield this._daoModel.query(sqlhuxing);
        let arrhxResult = hxResult.rows
        for (let i = 0; i < arrhxResult.length; i++) {
            let hxtotal=arrhxResult[i].ckzj
            if(hxtotal&&hxtotal!='null'){
                hxtotal=hxtotal/10000
            }else{
                hxtotal=0
            }
            let sql = `INSERT INTO home_base_hx (pid, lpname, name, jjx, tags, jzmj, pics, xszt, ckzj, note, lphx_id, cx, 
                sort, room, hall, toilet, status, tedian, mianji_zengsong, mianji_taonei, mianji_gongtan, 
                create_time, loupan_id,  city_id, company_id, site_id, ishot, is_kaijian) 
                VALUES ('`+0+`', '`+hxResult.rows[i].lpname+`', '`+hxResult.rows[i].title+`', '`+hxResult.rows[i].jjx+`', '`+hxResult.rows[i].tags+`', '`+hxResult.rows[i].jzmj+`', 
                '`+hxResult.rows[i].pic+`', '`+hxResult.rows[i].xszt+`', '`+hxtotal+`', '合并数据', '`+hxResult.rows[i].lphx_id+`', '`+hxResult.rows[i].cx+`', 
                '`+hxResult.rows[i].sort+`', '`+hxResult.rows[i].room+`', '`+hxResult.rows[i].hall+`', '`+hxResult.rows[i].toilet+`', '`+hxResult.rows[i].status+`', '`+hxResult.rows[i].tedian+`', 
                '`+hxResult.rows[i].mianji_zengsong+`', '`+hxResult.rows[i].mianji_taonei+`', '`+hxResult.rows[i].mianji_gongtan+`', '`+moment(hxResult.rows[i].create_time).format('YYYY-MM-DD')+`', '`+hxResult.rows[i].loupan_id+`', 
                '`+hxResult.rows[i].city_id+`', '`+hxResult.rows[i].company_id+`', '`+hxResult.rows[i].site_id+`', '`+hxResult.rows[i].ishot+`', '`+hxResult.rows[i].is_kaijian+`')`
            let result = yield this._daoModel.query(sql);
        }

        //查询haojia_dongtai_copy1表
        let sqldy = `SELECT * FROM haojia_dongtai_copy1`
        let dyResult = yield this._daoModel.query(sqldy);
        let arrdyResult = dyResult.rows
        for (let i = 0; i < arrdyResult.length; i++) {
            let sql = `INSERT INTO home_dynamic (pid, time, title, content, type, note, start_time, 
                author, status, pic, city_id, creater, sort, site_id, company_id,loupan_id) 
                VALUES ('`+1+`', '`+moment(dyResult.rows[i].start_time).format('YYYY-MM-DD')+`', '`+dyResult.rows[i].title+`', '`+dyResult.rows[i].content+`', '0', '合并数据', '`+moment(dyResult.rows[i].start_time).format('YYYY-MM-DD')+`', 
                '`+dyResult.rows[i].author+`', '`+dyResult.rows[i].status+`', '`+dyResult.rows[i].pic+`', '`+dyResult.rows[i].city_id+`', 
                '`+dyResult.rows[i].creater+`', '`+dyResult.rows[i].sort+`', '`+dyResult.rows[i].site_id+`', '`+dyResult.rows[i].company_id+`', '`+dyResult.rows[i].loupan_id+`')`
            let result = yield this._daoModel.query(sql);
        }

        //查询haojia_loupan_ask_copy1表
        let sqlqa = `SELECT * FROM haojia_loupan_ask_copy1`
        let qaResult = yield this._daoModel.query(sqlqa);
        let arrqaResult = qaResult.rows
        for (let i = 0; i < arrqaResult.length; i++) {
            let sql = `INSERT INTO crm_user_yhq_qa (cat_id, que, ans, create_date,  status, 
                loupan_id, city_id, author, start_time, zan, sort, company_id, site_id) 
                VALUES ('0', '`+qaResult.rows[i].title+`', '`+qaResult.rows[i].content+`', '`+moment(qaResult.rows[i].create_time).format('YYYY-MM-DD')+`', '`+qaResult.rows[i].status+`', 
                '`+qaResult.rows[i].loupan_id+`', '`+qaResult.rows[i].city_id+`', '`+qaResult.rows[i].author+`', '`+moment(qaResult.rows[i].start_time).format('YYYY-MM-DD')+`', 
                 '`+qaResult.rows[i].zan+`', '`+qaResult.rows[i].sort+`', '`+qaResult.rows[i].company_id+`', '`+qaResult.rows[i].site_id+`')`
            let result = yield this._daoModel.query(sql);
        }

        //修改同步过来的表的pid
        let sqlupdatetableid = `select id,lpid from home_base where lpid in (select id from haojia_loupan_copy1)`
        let updatetableidResult = yield this._daoModel.query(sqlupdatetableid);
        let arrupdatetableidResult = updatetableidResult.rows
        for (let i = 0; i < arrupdatetableidResult.length; i++) {
            let hbid=arrupdatetableidResult[i].id;
            let hblpid=arrupdatetableidResult[i].lpid;
            let sql1 = `UPDATE home_dynamic set pid='${hbid}' where loupan_id='${hblpid}'`
            let resultq = yield this._daoModel.query(sql1);
            let sql2 = `UPDATE home_base_hx set pid='${hbid}' where loupan_id='${hblpid}'`
            let resultw = yield this._daoModel.query(sql2);
            let sql3 = `UPDATE crm_user_yhq_qa set pid='${hbid}' where loupan_id='${hblpid}'`
            let resulte = yield this._daoModel.query(sql3);
        }


        //修改homeBase表中的值为null的数据
        let sqlupdatenull = `UPDATE home_base set lczk='' where lczk='null';
        UPDATE home_base set jiegou='' where jiegou='null';
        UPDATE home_base set rooms='' where rooms='null';
        UPDATE home_base set tag='' where tag='null';
        UPDATE home_base set desc_zhoubian='' where desc_zhoubian='null';
        UPDATE home_base set desc_youshi='' where desc_youshi='null';
        UPDATE home_base set jfsj='' where jfsj='null';
        UPDATE home_base set kpsj='' where kpsj='null';
        UPDATE home_base set kaipan_date=null WHERE  kaipan_date='0000-00-00';
UPDATE home_base set create_time=null WHERE  create_time='0000-00-00';
UPDATE home_base set update_time=null WHERE  update_time='0000-00-00';
UPDATE home_base set tips_limit_time=null WHERE  tips_limit_time='0000-00-00';
UPDATE crm_user_yhq_qa set create_date=null WHERE  create_date='0000-00-00';
UPDATE crm_user_yhq_qa set start_time=null WHERE  start_time='0000-00-00';
UPDATE home_base_hx set create_time=null WHERE  create_time='0000-00-00';
UPDATE home_dynamic set time=null WHERE  time='0000-00-00';
UPDATE home_dynamic set start_time=null WHERE  start_time='0000-00-00';`
        let updatenullResult = yield this._daoModel.query(sqlupdatenull);



        let sqlQueryIsNullHomeBase = `SELECT id FROM home_base where total_min is NULL`
        let sqlQueryIsNullHomeBaseResult = yield this._daoModel.query(sqlQueryIsNullHomeBase);
        let sqlQueryIsNullHomeBaseIdArr = sqlQueryIsNullHomeBaseResult.rows
        for (let i = 0; i < sqlQueryIsNullHomeBaseIdArr.length; i++) {
            let homeBaseId=sqlQueryIsNullHomeBaseIdArr[i].id
            let sqlQueryHomeBase = `SELECT MAX(jzmj) maxJzmj,MIN(jzmj) minJzmj,MAX(ckzj) maxCkzj,MIN(ckzj) minCkzj FROM home_base_hx WHERE pid=${homeBaseId} and xszt=0 GROUP BY pid;            `
            let sqlQueryHomeBaseResult = yield this._daoModel.query(sqlQueryHomeBase);
            let sqlQueryHomeBaseIdArr = sqlQueryHomeBaseResult.rows[0]
            // return {sqlQueryHomeBaseIdArr:sqlQueryHomeBaseIdArr}
            if(sqlQueryHomeBaseIdArr){
                let maxJzmj=sqlQueryHomeBaseIdArr.maxJzmj
                let minJzmj=sqlQueryHomeBaseIdArr.minJzmj
                let minCkzj=sqlQueryHomeBaseIdArr.minCkzj
                let maxCkzj=sqlQueryHomeBaseIdArr.maxCkzj
                let sqlUpdateHomeBase = `UPDATE home_base set total_min='${minCkzj}',total_max='${maxCkzj}',mianji_min='${minJzmj}',mianji_max='${maxJzmj}'  where id='${homeBaseId}'`
                let sqlUpdateHomeBaseResult = yield this._daoModel.query(sqlUpdateHomeBase);
            }else{
                let sqlUpdateHomeBase = `UPDATE home_base set total_min='0',total_max='0',mianji_min='0',mianji_max='0'  where id='${homeBaseId}'`
                let sqlUpdateHomeBaseResult = yield this._daoModel.query(sqlUpdateHomeBase);
            }
        }
        console.log('===='+str)
        r.str=str
        return { code: 1, successed: true, msg: "修改成功！", rows: r }
    }
   

}
exports = module.exports = ActivityController;